<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
    <th:block th:replace="welcome :: static-file"></th:block>
</head>
<body>
<th:block th:replace="welcome :: navbar"></th:block>
<div class="layui-container">

    <table id="demo" lay-filter="test"></table>
    <div class="layui-row">
        <div class="layui-col-md6">
            <form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">密码</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
        <div class="layui-col-md6">

            <form class="layui-form" action="" id="edit" lay-filter="edit-form" style="display:none">
                <input type="hidden" name="userId" id="selectedId">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input  type="text" class="layui-input" id="selectedUser" name="roleName" disabled >
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">角色选择</label>
                    <div class="layui-input-block"  id="role-checkbox">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">已有角色</label>
                    <div class="layui-form-mid layui-word-aux" id="hasRole"></div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="editForm">立即提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>

        </div>
    </div>
</div>
</body>
<script>
var listTable ;
var form ;
layui.use('table', function(){//监听提交

  var table = layui.table;
  //第一个实例
  listTable = table.render({
    elem: '#demo'
    ,height: 312
    ,url: '/user/all' //数据接口
    // ,page: true //开启分页
    ,cols: [
    [ //表头
        {field: 'id', title: 'ID', width:80, sort: true, fixed: 'left'}
      ,{field: 'username', title: '用户名', }
      ,{field: 'password', title: '密码',   sort: true}
    ]
    ]
  });
    //监听行单击事件
    table.on('row(test)', function(obj){
       $("#edit").css('display','block');
       $('#selectedUser').val(obj.data.username)
       $('#selectedId').val(obj.data.id)
       getRoleByUserId(obj.data.id)
      //console.log(obj.tr) //得到当前行元素对象
      //console.log(obj.data) //得到当前行数据
      //obj.del(); //删除当前行
      //obj.update(fields) //修改当前行数据

    });
});
function getRoleByUserId(userId){
     $.get({
        url:'/user/get/role/' +userId,
         success:function(resp){
            if(! resp.data) return;
            had = resp.data.map(ele => ele.roleName)
            $("#hasRole").text(had)
         }
     });
}
layui.use('form', function(){
  form = layui.form;
  //监听提交
  form.on('submit(formDemo)', function(data){
    $.post({
        url:'/user/register',
        data: JSON.stringify(data.field),
        contentType:'application/json',
        success:function(resp){
            if (resp.ok){
                layer.msg(`用户${data.field.username}注册成功`);
                $("button[type='reset']").click()
            }
            else  layer.msg(`用户${data.field.username}注册失败!${resp.msg}`)
        }
    })
    return false;
  });

  form.on('submit(editForm)',function(data){
        var chk_value =[];
        $('input:checkbox:checked').each(function(){
            chk_value.push(parseInt($(this).val()));
        });
        var dt = { 'userId': parseInt($('#selectedId').val()) , 'roleIds' : chk_value}
        $.post({
            url:'/user/add/role',
            data: JSON.stringify(dt),
            contentType:'application/json',
            success:function(resp){
                if (resp.ok){
                    layer.msg(`用户${data.field.roleName}角色修改成功`);
                }
            }
        })
    });
});
$(function(){
     getAllRole();
});
function getAllRole(){
    $.get({
        url:'/role/all',
        success:function(resp){
            if(resp.data){
                var checkbox = $("#role-checkbox")
                checkbox.empty();
                for (var ele of resp.data){
                    var op = $(` <input type="checkbox" title="${ele.roleName}"  name="roleIds" value="${ele.id}" /> `)
                    checkbox.append(op)
                }
                form.render('checkbox','edit-form');
            }else{
                layer.msg(`没有找到信息！`)
            }
        }
    });
}

</script>
</html>